﻿var jsonData;
var currentUser = undefined;
var designer; //Variable used to save the designer plugin
var vcard;
var defRelProps;
var defRelItems;
var defFeaProps;
var defIteProps;
var defIteItems;
var defStatProps;
var defStatItems;
var statuses;
var loginWindow;
var headerSettingsLinkEl, helpPanelOpenEl, settingsWin, reportBugEl, calendarLinkEl, calendarWin, logoutEl, switchUserEl;
var defaultStats = { Done: 0, InProgress: 2, NotDone: 1 };
var defaultStatuses = { Done: "Done", InProgress: "InProgress", NotDone: "NotDone" };
var defaultStatsText = { Done: "Done", InProgress: "In Progress", NotDone: "Not Done" };

var etypes = { card: "card", container: "container", ccard: "ccard", iteration: "Iteration", release: "Release", project: "Project" };

var reportError = "mailto:yogsbreath@gmail.com?subject=I found a bug";

var oops = { title: "Oops!, looks like you found a problem", msg: "If you continue to have this problem, please contact <a href='" + reportError + "' >yogsbreath@gmail.com</a>. <br/><br/> <b>Message content:</b> <br/>" };

function getLastItem(items) {
    return items[items.length - 1];
}

var excludeClms = { CreateTime: "CreateTime", Creator: "Creator" };

var excludeTaskClms = { StoryColor: "StoryColor" };

var excludeStoryClms = { FeatureColor: "FeatureColor" };

function ExcludeCm(name) {
    return excludeTaskClms[name] || excludeStoryClms[name] || excludeClms[name];
}

function IsDefaultStatus(name) {
    if (name == defaultStats.Done || name == defaultStats.InProgress || name == defaultStats.NotDone) return true;
    else if (name == defaultStatuses.Done || name == defaultStatuses.InProgress || name == defaultStatuses.NotDone) return true;
    else return false;
}

function GetDefaultStatus(name) {
    if (name == defaultStats.Done || name == defaultStatuses.Done) return defaultStats.Done;
    else if (name == defaultStats.InProgress || name == defaultStatuses.InProgress) return defaultStats.InProgress;
    else if (name == defaultStats.NotDone || name == defaultStatuses.NotDone) return defaultStats.NotDone;
    else return null;
}

function isInProgress(name) {
    if (name == defaultStats.InProgress || name == defaultStatuses.InProgress) return true;
    else return false;
}

function helpUpdaterSetEvents() {
    var questionLnks = Ext.DomQuery.select(".helpQuestion", this.getEl().dom);
    var backLnks = Ext.DomQuery.select(".helpBack", this.getEl().dom);
    var pnl = this;
    Ext.each(questionLnks, (function(itm, idx, len) {
        Ext.get(itm).on("click", (function() {
            pnl.load({
                url: "../Help/Help/?r=" + Math.random() + "&question=" + itm.getAttribute("id")
            });
        }));
    }));
    Ext.each(backLnks, (function(itm, idx, len) {
        Ext.get(itm).on("click", (function() {
            pnl.load({
                url: "../Help/Help/?r=" + Math.random()
            });
        }));
    }));
}; // end helpUpdaterSetEvents

function isNotDone(name) {
    if (name == defaultStats.NotDone || name == defaultStatuses.NotDone) return true;
    else return false;
}

function isDone(name) {
    if (name == defaultStats.Done || name == defaultStatuses.Done) return true;
    else return false;
}

function formatStatus(name) {    
    if (name == 0) return defaultStatsText.Done;
    else if (name == 1) return defaultStatsText.NotDone;
    else if (name == 2) return defaultStatsText.InProgress;
    else return name;
}

function trimAll(value) { return value.replace(/^\s+/, '').replace(/\s+$/, ''); }

function formatTime(value) {
    if (!value || value == null) return "0.0";

    if (value.toString().indexOf(".") == -1) return value + ".0";
    else return value;
}

function CC_changetype(target, wrde) {
    var inp = document.createElement('input');
    inp.name = inp.id = 'txtPass';
    inp.width = 265;
    inp.style.cssText = target.style.cssText;
    var parent = target.parentNode;

    if (target.value == wrde) {
        inp.type = 'password';
        inp.value = '';
        inp.maxLength = 8;
        inp.setAttribute('onblur', target.getAttribute('onfocus'));
        inp.setAttribute('onfocus', 'this.select();');
        var fcs = true;
    }
    else if (target.value == '') {
        inp.type = 'text';
        inp.maxLength = 99;
        inp.value = wrde;
        inp.setAttribute('onfocus', target.getAttribute('onblur'));
    }
    if (target.value == wrde || target.value == '') {
        parent.insertBefore(inp, target);
        parent.removeChild(target);
    }
    try {
        if (fcs) {
            inp.focus();
            //inp.select();
        }
    } catch (ex) {
    }
}

function helpPanelOpenFn() {

    //getCmps().helpOwnerCt.setWidth((Ext.getBody().getWidth() * 0.33));
    getCmps().helpOwnerCt.toggleCollapse();
}; // end helpPanelOpenFn

function calendarPanelOpenFn() {
    
    calendarWin = calendarWin || new dlr.cmp.workSpace.calendarWindow();
    calendarWin.show();
}; // end calendarPanelOpenFn

function calendarPanel() {
    var table = new Ext.Window({
        title: 'Table Layout',
        layout: 'table',
        defaults: {
            // applied to each contained panel
            bodyStyle: 'padding:20px'
        },
        layoutConfig: {
            // The total column count must be specified here
            columns: 3
        },
        items: [{
            html: '<p>Cell A content</p>',
            rowspan: 2
        }, {
            html: '<p>Cell B content</p>',
            colspan: 2
        }, {
            html: '<p>Cell C content</p>',
            cellCls: 'highlight'
        }, {
            html: '<p>Cell D content</p>'
}]
        });
        table.show();
    };

    function setEvents() {

        if (!headerSettingsLinkEl) {
            headerSettingsLinkEl = Ext.get("headerSettingsLink");
            headerSettingsLinkEl.dom.disabled = false;
        }
        headerSettingsLinkEl.un("click", headerSettingFn);
        headerSettingsLinkEl.on("click", headerSettingFn);

        if (!calendarLinkEl) {
            calendarLinkEl = Ext.get("calWinLink");
            calendarLinkEl.dom.disabled = false;
        }
        calendarLinkEl.un("click", calendarPanelOpenFn);
        calendarLinkEl.on("click", calendarPanelOpenFn);

        if (!helpPanelOpenEl) {
            helpPanelOpenEl = Ext.get("helpPanelOpen");
            helpPanelOpenEl.dom.disabled = false;
        }
        helpPanelOpenEl.un("click", helpPanelOpenFn);
        helpPanelOpenEl.on("click", helpPanelOpenFn);

        if (!logoutEl) {
            logoutEl = Ext.get("logout");
            logoutEl.dom.disabled = false;
        }

        if (!reportBugEl) {
            reportBugEl = Ext.get("reportBug");
        }

        reportBugEl.on("click", function() {
            location.href = "mailto:yogsbreath@gmail.com?subject=I found a bug"
        });

    }; // setEvents

    function headerSettingFn() {
        settingsWin = settingsWin || new dlr.cmp.workSpace.settingsWindow();
        settingsWin.show();
    }; // end headerSettingFn

    function getCmps() {
        return {
            //queueOwnerCt: that.items.get(1),
            //queueBbarSaveBtn: that.items.get(1).getTopToolbar().items.get(0),
            //queueBbarStartBtn: that.items.get(1).getTopToolbar().items.get(0),
            //queueBbarArchiveBtn: that.items.get(1).getTopToolbar().items.get(1),
            //queueBbarDeleteBtn: that.items.get(1).getTopToolbar().items.get(2),
            //queueGrid: that.items.get(1).items.get(0),
            //tabPanelOwnerCt: that.items.get(2),
            helpOwnerCt: Ext.getCmp('helpPanel'),
            frmAccount: Ext.getCmp('frmAccount'),
            frmop: Ext.getCmp('OldPassword'),
            frmnp: Ext.getCmp('NewPassword'),
            grdUsers: Ext.getCmp('ExtGridPanel1')
        };
    }; // end getCmps

    // ------------------------------------------------
    // private functions
    // ------------------------------------------------
    function getSetCmps() {
        if (!settingsWin) return;
        return {
            frmProject: settingsWin.items.get(0).items.get(0).items.get(0),
            frmTeam: settingsWin.items.get(0).items.get(1).items.get(0),
            frmUserName: settingsWin.items.get(0).items.get(0).items.get(0).items.get(0),
            frmop: settingsWin.items.get(0).items.get(0).items.get(0).items.get(1),
            frmnp: settingsWin.items.get(0).items.get(0).items.get(0).items.get(2),
            frmcp: settingsWin.items.get(0).items.get(0).items.get(0).items.get(3),
            frmFirstName: settingsWin.items.get(0).items.get(0).items.get(0).items.get(4),
            frmLastName: settingsWin.items.get(0).items.get(0).items.get(0).items.get(5),
            frmEmail: settingsWin.items.get(0).items.get(0).items.get(0).items.get(6),
            grdUsers: Ext.getCmp('ExtGridPanel1')
        };
    }; // end getSetCmps

    function takeYear(theDate) {
        x = theDate.getYear();
        var y = x % 100;
        y += (y < 38) ? 2000 : 1900;
        return y;
    }

    function leadingZero(nr) {
        if (nr < 10) nr = "0" + nr;
        return nr;
    }

    function getMSDate(val) {

        var dt;
        (!Ext.isDate(val)) ? dt = new Date(val) : dt = val;

        return '/Date(' + dt.getTime() + ')/'
    }

    function convertDate(v, mix) {
        return new Date(parseFloat(v.slice(6, 19))).toLocaleString();
    }

    Date.patterns = {
        ISO8601Long: "Y-m-d H:i:s",
        ISO8601Short: "Y-m-d",
        ShortDate: "n/j/Y",
        DisplayDate: "m/d/Y",
        TitleDate: "m-d-Y",
        LongDate: "l, F d, Y",
        FullDateTime: "l, F d, Y g:i:s A",
        MonthDay: "F d",
        ShortTime: "g:i A",
        LongTime: "g:i:s A",
        SortableDateTime: "Y-m-d\\TH:i:s",
        UniversalSortableDateTime: "Y-m-d H:i:sO",
        YearMonth: "F, Y"
    };

    function formatDate(obj, format) {
        if (obj == null || obj == "") return "";
        if (!Ext.isDate(obj) && obj.indexOf('/Date(') > -1) {
            var ms = obj.substring(6);
            ms = ms.substring(0, ms.indexOf(')/'));

            obj = new Date(parseInt(ms));
        }

        if (format == 'd') {
            return leadingZero(obj.getMonth() + 1) + "/" + leadingZero(obj.getDate()) + "/" + obj.getFullYear();
        } else {
            return obj.getFullYear() + "-" + leadingZero(obj.getMonth() + 1) + "-" + leadingZero(obj.getDate());
        }
    }

    function formatMSDate(obj, pattern) {
        if (!obj) return null;
        if (Ext.isDate(obj)) return pattern ? obj.format(pattern) : obj;
        if (obj.indexOf('/Date(') > -1) {
            var ms = obj.substring(6);
            ms = ms.substring(0, ms.indexOf(')/'));

            obj = new Date(parseInt(ms));

            return pattern ? obj.format(pattern) : obj;
        }
    }

    function trimAll(sString) {
        while (sString.substring(0, 1) == ' ') {
            sString = sString.substring(1, sString.length);
        }
        while (sString.substring(sString.length - 1, sString.length) == ' ') {
            sString = sString.substring(0, sString.length - 1);
        }
        return sString;
    }

    function addItem(el) {
        var text = el.text.replace("Add", "");
        var designEl = designer;
        var propEl = defRelProps;
        var itemsEl = text != "Release" ? defRelItems : null;
        var feaEl = text == "Release" ? defFeaProps : null;

        if (text.toLowerCase() == "iteration") {
            designEl = relDesigner;
            propEl = defIteProps;
            itemsEl = defIteProps;
        }
        else if (text.toLowerCase() == "status") {
            designEl = sprintDesigner;
            propEl = defStatProps;
            itemsEl = defStatItems;
        }

        designer.addProjectItem(designEl, text + "Layout", text, propEl, itemsEl, feaEl);
    }; // end startQueue

    function getButton(text, tooltip, icon) {
        return {
            text: "Add" + text,
            iconCls: 'new-tab',
            icon: "../../Content/icons/" + icon,
            tooltip: tooltip,
            handler: this.toolbarHandler
        }
    }

    function addDesigner(el, etype, containerType, params, url, id, closable, title) {
        var panelObj = Ext.getCmp(el);
        var close = closable || false;
        var text = title || "";
        var elId = id || Ext.id;
        var tbar = [];

        if (etype == "Project") {
            tbar.push(getButton("Release", "Click here to add new Release", "addapp.png"));
            tbar.push(getButton("Feature", "Click here to add new Feature", "add.png"));
        }
        else if (etype == "Release") {
            tbar.push(getButton("Iteration", "Click here to add new Iteration", "addapp.png"));
            tbar.push(getButton("Story", "Click here to add new Story", "add.png"));
        }
        else if (etype == "Iteration") {
            tbar.push(getButton("Status", "Click here to add new Status", "addapp.png"));
            tbar.push(getButton("Task", "Click here to add new Task", "add.png"));
        }

        panelObj.add({
            id: elId,
            border: false,
            layout: 'fit',
            etype: 'container',
            xtype: 'panel',
            closable: close,
            title: text,
            bodyBorder: false,
            style: 'padding:0px 0px;',
            items: {
                border: false,
                bodyBorder: false,
                bodyStyle: 'background:transparent url(../../Content/images/grass.gif) bottom repeat-x;',
                xtype: 'jsonpanel',
                plugins: [new Extx.cmp.workSpace(
                        {
                            containerType: containerType,
                            url: url,
                            params: params,
                            parentEl: 'ProjectPanel',
                            urls: {},
                            autoLoad: true,
                            authenticate: false
                        }
                        )]
            }
        });

        panelObj.doLayout();
        return this.designerUI;
    }

    function fnLogin(btn, text) {
        if (btn == 'ok') {
            Ext.MessageBox.show({
                msg: 'Authenticating, please wait',
                progressText: 'Logging in...',
                width: 300,
                wait: true,
                waitConfig: {
                    interval: 200
                }
            });
            var target = Ext.get('txtPass').dom;
            var formValue = target.value;
            var parent = target.parentNode;
            //parent.removeChild(target);

            Ext.Ajax.request({
                url: '../Login/Authenticate',
                method: 'POST',
                params: { name: Ext.get('divProject').dom.innerText, password: formValue },
                callback: function(options, success, response) {
                    if (success) {
                        Ext.MessageBox.hide();
                        var result = Ext.util.JSON.decode(response.responseText)
                        if (result.Result) {
                            designer = addDesigner('ProjectPanel', 'Project', 'Project', { projectId: 'ddddd' });
                        } else {
                            //Ext.MessageBox.alert("Message", result.Message);                                        
                            Ext.MessageBox.show({
                                msg: result.Message,
                                width: 300,
                                closable: false,
                                inputType: 'password',
                                allowBlank: false,
                                buttons: Ext.Msg.OKCANCEL,
                                prompt: true,
                                fn: fnLogin
                            });
                            //CC_changetype(Ext.MessageBox.getDialog().body.child('input').dom, '')
                        }
                    } else {
                        Ext.MessageBox.hide();
                        Ext.MessageBox.alert("Failure, please try again", response.responseText);
                    }
                },
                // the function to be called upon failure of the request
                // (server script, 404, or 403 errors)
                failure: function(response, options) {
                    Ext.MessageBox.hide();
                    ReturnValue = Ext.MessageBox.alert("Warning, There was an unexpected error! Please contact administrator！");
                },
                success: function(response, options) {
                    Ext.MessageBox.hide();
                }
            })// end Ajax request

        } else if (btn == 'cancel') {
            window.location = "http://localhost:1207";
        }
    };

    function basicVal(val) {
        var myRegxp = /^([a-zA-Z0-9_-]+)$/;
        var isVal = true;
        if (myRegxp.test(val) == false) {
            isVal = "Only Letters and Numbers are Allowed.";
        }
        if (val.length < 3) {
            isVal = "Must be More Than 3 Characters.";
        }
        return isVal;
    }; // end basicVal

    function deleteRecord(btn) {
        if (btn == 'yes') {
            var selectedRows = getCmps().grdUsers.selModel.selections.items;
            var selectedKeys = getCmps().grdUsers.selModel.selections.keys;
            Ext.MessageBox.show({
                msg: 'Data is requested, please wait',
                progressText: 'Request data is',
                width: 300,
                wait: true,
                waitConfig: {
                    interval: 200
                }
            });
            Ext.Ajax.request({
                url: '../User/DeleteUser',
                method: 'POST',
                params: {
                    "userid": selectedKeys
                }, // the unique id(s)
                callback: function(options, success, response) {
                    if (success) {
                        Ext.MessageBox.hide();
                        var result = Ext.util.JSON.decode(response.responseText)
                        //Ext.MessageBox.alert("Message", result.Message);
                    } else {
                        Ext.MessageBox.hide();
                        Ext.MessageBox.alert("Failure, please try again", response.responseText);
                    }
                },
                // the function to be called upon failure of the request
                // (server script, 404, or 403 errors)
                failure: function(response, options) {
                    Ext.MessageBox.hide();
                    ReturnValue = Ext.MessageBox.alert("Warning, There was an unexpected error! Please contact administrator！");
                },
                success: function(response, options) {
                    Ext.MessageBox.hide();
                    Ext.getCmp('ExtGridPanel1').store.reload();
                }
            })// end Ajax request
        } // end if click 'yes' on button
    } // end deleteRecord